import type { Directive, DirectiveBinding } from 'vue';
import { type ICopyElement } from './type.d';
import { useEventListener } from '@vueuse/core';

/**
 * 文本复制指令（默认双击复制）
 */
export const copy: Directive = {
  mounted(el: ICopyElement, binding: DirectiveBinding<string>) {
    const { value } = binding;
    if (value) {
      el.copyValue = value;
      const arg = binding.arg ?? 'dblclick';
      //卸载会自动清理，无需手动清理
      useEventListener(el, arg, async () => {
        const copyValue = el.copyValue;
        navigator.clipboard.writeText(copyValue).then(() => {
          console.log('复制成功');
        });
      });
    } else {
      throw new Error('[Directive: copy]: need value! Like v-copy="modelValue"');
    }
  },
  updated(el: ICopyElement, binding: DirectiveBinding) {
    el.copyValue = binding.value;
  },
};
